package com.example.demo.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * @Author: kaka
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Res<T> implements Serializable {

    /**
     * tlog中mdc的traceId
     */
    public static final String TLOG_TRACE_KEY = "tlogTraceId";

    /**
     * 日志链路traceId
     */
    private String traceId;
    /**
     * 响应码
     */
    private Integer code;
    /**
     * 响应码说明
     */
    private String msg;
    /**
     * 响应是否成功
     */
    private Boolean isSuccess;
    /**
     * 响应数据
     */
    private T data;

    public static <T> Res<T> of(T data, Integer code, String msg) {
        return new Res<T>(MDC.get(TLOG_TRACE_KEY), code, msg, BizCodeEnum.SUCCESS.getCode().equals(code), data);
    }

    public static <T> Res<T> succeed() {
        return of(null, BizCodeEnum.SUCCESS.getCode(), BizCodeEnum.SUCCESS.getMsg());
    }

    public static <T> Res<T> succeed(T model, String msg) {
        return of(model, BizCodeEnum.SUCCESS.getCode(), msg);
    }

    public static <T> Res<T> succeed(T model) {
        return of(model, BizCodeEnum.SUCCESS.getCode(), "");
    }

    public static <T> Res<T> failed() {
        return of(null, BizCodeEnum.FAIL.getCode(), BizCodeEnum.FAIL.getMsg());
    }

    public static <T> Res<T> failed(BizCodeEnum bizCodeEnum, String msg) {
        return of(null, bizCodeEnum.getCode(), msg);
    }

    public static <T> Res<T> failed(BizCodeEnum bizCodeEnum) {
        return of(null, bizCodeEnum.getCode(), bizCodeEnum.getMsg());
    }

    public static <T> Res<T> failed(String msg) {
        return of(null, BizCodeEnum.FAIL.getCode(), msg);
    }

    public static <T> Res<T> failed(Integer code, String msg) {
        return of(null, code, msg);
    }

    public static <T> Res<T> failed(T model, String msg) {
        return of(model, BizCodeEnum.FAIL.getCode(), msg);
    }


}
